package com.zzyk.main.configuration.aspectj;

import com.zzyk.main.configuration.exception.UserException;

import com.zzyk.main.model.pojo.SysRole;
import com.zzyk.main.service.ISysRoleService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;

@Aspect
@Component
@EnableAsync
public class RoleAspect {
    @Autowired
    private ISysRoleService sysRoleService;

    @Pointcut("execution(public * com.zzyk.*.controller.SysRoleController.saveRole(..))")
    public void roleSavePoint() {
    }

    @Pointcut("execution(public * com.zzyk.*.controller.SysRoleController.delRole(..))")
    public void roleDelPoint() {
    }

    @Before("roleSavePoint()")
    public void beforeSaveRole(JoinPoint joinPoint) throws UserException {
        if (joinPoint.getArgs() != null && joinPoint.getArgs()[0] != null && joinPoint.getArgs()[0] instanceof SysRole) {
            SysRole role = (SysRole) joinPoint.getArgs()[0];
            if (role.getId() != null) {
                SysRole sysRole = sysRoleService.getRole(role.getId());
                if (sysRole.getReadonly() == 1) {
                    throw new UserException("禁止修改内置用户");
                }
            }
        }
    }

    @Before("roleDelPoint()")
    public void beforeDelRole(JoinPoint joinPoint) throws UserException {
        if (joinPoint.getArgs() != null && joinPoint.getArgs()[0] != null) {
            Integer id = (Integer) joinPoint.getArgs()[0];
            SysRole sysRole = sysRoleService.getRole(id);
            if (sysRole == null) {
                throw new UserException("角色不存在");
            } else if (sysRole.getReadonly() == 1) {
                throw new UserException("禁止删除内置用户");
            }
        }
    }
}
